package com.vegetable.modules.service.bank.convert;


import cn.hutool.core.date.DateUtil;
import com.vegetable.modules.entity.finance.Transactions;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.multipart.MultipartFile;

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * 潍坊流水标准化字段输出
 */
@Slf4j
public class WFBConverter extends BankGenerator {
	private static final String bankMark = "WFBC";
	public List<Transactions> convert(MultipartFile file) throws Exception {
		List<Transactions> result = new ArrayList<>();
		try (Workbook workbook = WorkbookFactory.create(file.getInputStream())) {
			Sheet sheet = workbook.getSheetAt(0);
			int lastRow = sheet.getLastRowNum();
			for(int i = 1; i < lastRow; i++){
				Row currentR = sheet.getRow(i);
				try {
					Transactions thisT = getTransactions(currentR);
					result.add(thisT);
				}catch (Exception e){
					log.error("转换潍坊银行流水发生异常，第{}行有问题", i);
					e.printStackTrace();
				}
			}
		}catch (Exception e){
			log.error("转换潍坊银行流水发生异常--->", e);
			return null;
		}
		return result;
	}

	@NotNull
	private Transactions getTransactions(Row currentR) throws Exception {
		Transactions thisT = new Transactions();
		NumberFormat format = NumberFormat.getNumberInstance();
		int inAmount = format.parse(getStringCell(currentR,2).trim()).intValue();
		thisT.setTradingType(inAmount == 0 ? "EXPENSE" : "INCOME");
		thisT.setTradingTime(DateUtil.parse(getStringCell(currentR,1)));
		thisT.setTradingAmount("INCOME".equals(thisT.getTradingType()) ? getBCCell(currentR,2) : getBCCell(currentR,3));
		thisT.setBalanceAmount(getBCCell(currentR,4));
		thisT.setBankName(getStringCell(currentR,9));
		thisT.setBankNo(getStringCell(currentR,7));
		thisT.setCounterparty(getStringCell(currentR,8));
		thisT.setTradingDescription(getStringCell(currentR,10));
		thisT.setTradingNo(Transactions.generateUniqueFlowId(thisT));
		thisT.setChannel(bankMark);
		return thisT;
	}
}
